<!DOCTYPE html>
<html xmlns:th="http://www.thymeleaf.org">
<head th:replace="common/common :: common_header"/>
<style>
    .label-status {
        display: inline;
        padding: .2em .6em .2em;
        font-size: 100%;
        line-height: 2;
        color: #fff;
        text-align: center;
        white-space: nowrap;
        vertical-align: baseline;
        border-radius: .25em
    }
</style>
<body>
<div data-toggle="topjui-layout" data-options="fit:true">
    <!--<div data-options="region:'west',split:true,width:'10%',iconCls:'fa fa-sitemap',border:false,bodyCls:'border_right'">
        左侧区域
    </div>-->
    <div data-options="region:'center',iconCls:'icon-reload',title:'',split:true,border:false">
        <div data-toggle="topjui-layout" data-options="fit:true">
            <div data-options="region:'center',fit:false,split:true,border:true,bodyCls:'border_top_none'">
                <div data-toggle="topjui-tabs" data-options="border:false">
                    <div title="角色列表" data-options="iconCls:'fa fa-table'">
                        <table id="roleList" data-toggle="topjui-datagrid"
                               data-options="id:'roleList',
                                         idField:'id',
                                         pagination:true,url:'../../role/list',
                                         fitColumns:false,
                                         rownumbers: true,
                                         singleSelect:true,
                                         selectOnCheck:false,
                                         checkOnSelect:false,
                                         childTab:[{id:'roleOtherDetailTab'}],
                                         onSelect:function(index,row){
                                            selectRoleClientAuthorize.length = 0;
                                            $('#selectRoleName').html(row.name);
                                         },
                                         rowStyler:function(index,row){
                                            if(row.status == 'DISABLE'){
                                                return 'background-color:#FFD2D2;';
                                            }
                                         },
                                         childGrid:{
                                             param:'roleId:id',
                                                grid:[
                                                    {type:'treegrid',id:'roleClientAuthorizeGird'},
                                                    {type:'treegrid',id:'clientList'}
                                                ]
                                         }">
                            <thead>
                            <tr>
                                <th data-options="field:'',title:'复选框',checkbox:true"></th>
                                <th data-options="field:'id',title:'主键ID',width:160"></th>
                                <th data-options="field:'name',title:'角色名称',width:150"></th>
                                <th data-options="field:'status',title:'可用状态',sortable:true,width:100,
                                    formatter:function(value,row,index){
                                            if (value == 'ENABLE') {
                                                return '<span class=\'label-status\' style=\'background-color:#449d44;\'>已启用</span>';
                                            } else if (value == 'DISABLE') {
                                                return '<span class=\'label-status\' style=\'background-color:#ec971f;\'>已禁用</span>';
                                            }
                                    }">
                                </th>
                                <th data-options="field:'description',title:'描述',width:450"></th>
                                <th data-options="field:'createTime',title:'创建时间',width:160,sortable:true,sortname:'create_time',
                                    formatter:function(value,row,index){
                                            return timestamp2Datetime(value,'Y-m-d H:i:s');
                                    }">
                                </th>
                                <th data-options="field:'updateTime',title:'最近更新时间',width:160,
                                    formatter:function(value,row,index){
                                            return timestamp2Datetime(value,'Y-m-d H:i:s');
                                    }">
                                </th>
                                <th data-options="field:'operate',title:'操作',formatter:operateFormatter,width:200"></th>
                            </tr>
                            </thead>
                        </table>
                        <div id="roleList-toolbar" class="topjui-toolbar"
                             data-options="grid:{type:'datagrid', id:'roleList'}">
                            <a href="javascript:void(0)" onclick="addClientView()" data-toggle="topjui-menubutton"
                               data-options="iconCls: 'fa fa-plus',btnCls: 'topjui-btn-green'">新增</a>
                            <a href="javascript:void(0)" onclick="roleEdit()" data-toggle="topjui-menubutton"
                               data-options="iconCls: 'fa fa-pencil-square-o', btnCls: 'topjui-btn-blue'">修改</a>
                            <a href="javascript:void(0)" onclick="batchDeleteClient()" data-toggle="topjui-menubutton"
                               data-options="btnCls:'topjui-btn-brown',iconCls:'fa fa-trash'">删除</a>
                            <!--<a href="javascript:void(0)" onclick="authorizeClient()"
                               data-toggle="topjui-menubutton" data-options="iconCls: 'fa fa-plus',btnCls: 'topjui-btn-black'">应用授权</a>-->
                        </div>
                        <form method="post" id="roleEditDialog"></form>
                    </div>
                </div>
            </div>
            <div data-options="region:'south',fit:false,split:true,bodyCls:'border_bottom_none'" style="height: 300px;">
                <div data-toggle="topjui-tabs" style="width:500px;height:350px;"
                     data-options="id:'roleOtherDetailTab',
                     fit:true,
                     border:false,
                     parentGrid:{
                         type:'datagrid',
                         id:'roleList',
                         param:'roleId:id'
                     }">
                    <div title="应用授权" data-options="id:'roleClientAuthorize',iconCls:'fa fa-plus',closable:false,selected:true">
                        <table id="roleClientAuthorizeGird" data-toggle="topjui-treegrid"
                               data-options="id:'roleClientAuthorizeGird',
                                        idField:'id',
                                        treeField:'name',
                                        url:'../../role/client/authorize/list',
                                        emptyMsg:'暂无数据',
                                        fitColumns:false,
                                        rownumbers: true,
                                        selectOnCheck:false,
                                        checkOnSelect:false,
                                        rowStyler:function(row){
                                            if (row.authorize == 'yesAuthorize') {
                                                return 'background-color:#D3EAAF;';
                                            }
                                        },
                                        onCheckAll:function(){
                                            var allClient = $('#roleClientAuthorizeGird').treegrid('getData');
                                            selectRoleClientAuthorize.length = 0;
                                            for(var i = 0; i < allClient.length; i++){
                                                selectRoleClientAuthorize.push(allClient[i].id);
                                            }
                                        },
                                        onUncheckAll:function(){
                                            selectRoleClientAuthorize.length = 0;
                                        },
                                        onCheck:function(row){
                                            selectRoleClientAuthorize.push(row.id);
                                        },
                                        onUncheck:function(row){
                                            selectRoleClientAuthorize.remove(row.id);
                                        }" >
                            <thead>
                            <tr>
                                <th data-options="field:'',title:'复选框',checkbox:true"></th>
                                <!--<th data-options="field:'id',title:'主键',width:100"></th>-->
                                <th data-options="field:'name',title:'应用名称',width:200"></th>
                                <th data-options="field:'authorize',title:'授权状态',width:100,
                                                            formatter:function(value,row,index){
                                                                if (value == 'yesAuthorize') {
                                                                    selectRoleClientAuthorize.push(row.id);
                                                                    return '<span class=\'label-status\' style=\'background-color:#449d44;\'>已授权</span>';
                                                                } else {
                                                                    return '<span class=\'label-status\' style=\'background-color:#ec971f;\'>未授权</span>';
                                                                }
                                                            }"></th>
                            </tr>
                            </thead>
                        </table>
                        <div id="roleClientAuthorizeGird-toolbar" class="topjui-toolbar" data-options="grid:{type:'treegrid', id:'roleClientAuthorizeGird'}">
                            <div style="margin-top: 3px;">
                                <blockquote class="layui-elem-quote" style="padding: 10px!important;border-left:5px solid #FFA500;">
                                    <p style="color:#FFA500">提示：不勾选即表示无权限访问</p>
                                </blockquote>
                            </div>
                            <a href="javascript:void(0)" onclick="roleClientAuthorize()"
                               data-toggle="topjui-menubutton" data-options="iconCls: 'fa fa-plus',btnCls: 'topjui-btn-green'">应用授权</a>
                            <span style="margin-left: 20px;font-weight: bold;">选中的角色：<span id="selectRoleName" style="color: red;font-weight: bold;font-size: 14px;">(暂未选择角色)</span></span>
                        </div>
                    </div>
                    <div title="角色详情" data-options="iconCls:'fa fa-list',closable:true,href:'../../role/detail/view?roleId={id}'" style="padding:20px;">
                        （tip：选中某一条角色数据即可显示出信息）
                    </div>
                    <div title="操作日志" data-options="id:'roleOperateLog',iconCls:'fa fa-plus',closable:true,selected:true">
                        <table data-toggle="topjui-datagrid"
                               data-options="id:'roleOperateLogGird',
                                        initCreate: false,
                                        idField:'id',
                                        url:'../../role/list/operate/log',
                                        fitColumns:true,
                                        pageSize:5,
                                        singleSelect:true,selectOnCheck:false,checkOnSelect:false">
                            <thead>
                            <tr>
                                <!--<th data-options="field:'',title:'复选框',checkbox:true"></th>-->
                                <th data-options="field:'id',title:'id',width:100"></th>
                                <th data-options="field:'operateUser',title:'操作账号',width:100"></th>
                                <th data-options="field:'operateIp',title:'操作IP',width:100"></th>
                                <th data-options="field:'roleName',title:'角色名称',width:100"></th>
                                <th data-options="field:'requestUrl',title:'请求URL',width:200"></th>
                                <th data-options="field:'createTime',title:'操作时间',width:150,
                                              formatter:function(value,row,index){
                                                  return timestamp2Datetime(value,'Y-m-d H:i:s');
                                              }"></th>
                                <th data-options="field:'description',title:'说明',width:200"></th>
                            </tr>
                            </thead>
                        </table>
                    </div>
                </div>
            </div>
        </div>
    </div>
    <div data-options="region:'east',iconCls:'fa fa-th',width:'30%',split:true,border:false">
        <div data-toggle="topjui-tabs" data-options="border:false">
            <div title="角色权限设置" data-options="iconCls:'fa fa-plus'">
                <div data-toggle="topjui-layout" data-options="fit:true">
                    <div data-options="region:'west',split:true,singleSelect:true,width:'40%',border:false,bodyCls:'border_left'" style="margin-top: 5px;border-right-width: 1px!important;">
                        <table data-toggle="topjui-treegrid" id="clientList"
                               data-options="id:'clientList',
                                        idField:'id',
                                        treeField:'name',
                                        url:'../../role/client/authorize/tree/list',
                                        singleSelect:true,
                                        childGrid:{
                                            param:'clientId:id,roleId:roleId',
                                            grid:[
                                                {type:'treegrid',id:'permissionList'},
                                            ]
                                        },
                                        onBeforeSelect:function(row){clientTreeClick(row)}">
                            <thead>
                            <tr>
                                <th data-options="field:'name',title:'角色已授权系统',width:180"></th>
                            </tr>
                            </thead>
                        </table>
                    </div>
                    <div data-options="region:'center',iconCls:'icon-reload',split:true,border:false">
                        <div data-toggle="topjui-layout" data-options="fit:true">
                            <div data-options="region:'center',iconCls:'fa fa-table',fit:false,split:true,border:false,bodyCls:'border_left'">
                                <div data-toggle="topjui-tabs" data-options="border:false">
                                    <div title="应用权限列表" data-options="iconCls:'fa fa-table'">
                                        <table data-toggle="topjui-treegrid" data-options="id:'permissionList',
                                                                            idField:'id',
                                                                            checkbox:true,
                                                                            cascadeCheck:false,
                                                                            treeField:'name',
                                                                            url:'../../role/client/permission/list/-1',
                                                                            expandUrl:'../../role/client/permission/list/{id}',
                                                                            emptyMsg:'暂无数据<br/><span style=\'color:green\'>温馨提示：点击左侧应用，查看具体权限配置</span>',
                                                                            singleSelect:true,selectOnCheck:false,checkOnSelect:false" id="permissionList">
                                            <thead>
                                            <tr>
                                                <!--<th data-options="field:'',title:'复选框',checkbox:true"></th>-->
                                                <!--<th data-options="field:'id',title:'主键',width:100"></th>-->
                                                <th data-options="field:'name',title:'权限名称',width:180"></th>
                                                <th data-options="field:'oauthStatus',title:'是否授权',width:100,
                                                            formatter:function(value,row,index){
                                                                if (value == 'yes') {
                                                                    return '<span class=\'label-status\' style=\'background-color:#449d44;\'>已授权</span>';
                                                                } else if (value == 'no') {
                                                                    return '<span class=\'label-status\' style=\'background-color:#ec971f;\'>未授权</span>';
                                                                }
                                                            }"></th>
                                            </tr>
                                            </thead>
                                        </table>
                                        <div id="permissionList-toolbar" class="topjui-toolbar" data-options="grid:{type:'treegrid', id:'permissionList'}">
                                            <div style="margin-top: 3px;">
                                                <blockquote class="layui-elem-quote" style="padding: 10px!important;border-left:5px solid #FFA500;">
                                                    <p style="color:#FFA500">提示：不勾选权限节点即表示取消操作权限</p>
                                                </blockquote>
                                            </div>
                                            <a href="javascript:void(0)" onclick="settingRoleClientPermission()"
                                               data-toggle="topjui-menubutton" data-options="iconCls: 'fa fa-plus',btnCls: 'topjui-btn-green'">赋予权限</a>
                                            <!--<a href="javascript:void(0)" onclick="cancelRoleClientPermission()"
                                               data-toggle="topjui-menubutton" data-options="iconCls: 'fa fa-trash', btnCls: 'topjui-btn-blue'">取消权限</a>-->
                                            <a href="javascript:void(0)" data-toggle="topjui-menubutton"
                                               data-options="onClick:expandAllPermissionNode,btnCls:'topjui-btn-red',iconCls:'fa fa-trash'">展开</a>
                                            <a href="javascript:void(0)" data-toggle="topjui-menubutton"
                                               data-options="onClick:collapseAllPermissionNode,btnCls:'topjui-btn-red',iconCls:'fa fa-trash'">折叠</a>
                                        </div>
                                    </div>
                                </div>
                            </div>
                        </div>
                    </div>
                </div>
            </div>
        </div>
    </div>
</div>


<script th:inline="javascript">
    //TODO: 获取项目上下文路径，记得需要在<script>标签中加入  th:inline="javascript" 属性配置，才可正常解析
    /*<![CDATA[*/
    var contextPath = /*[[@{/}]]*/;
    /*]]>*/

    /**
     * 应用tree节点单击事件
     */
    function clientTreeClick(row){
        if (row.id == -1) {
            //这里直接抛异常，就可以阻止一切代码的执行；目的是不让右侧表格进行数据加载刷新。这里如果返回 false，阻止不了右侧表格刷新，不知道是什么原因（如有知道解决办法的，请告知啊）
            throw "非真实应用系统的单击事件，不处理，直接跳过。（注意：这里并非功能上的异常，是人为解决问题的一种变通方式）";
        }
    }

    /**
     * 展开所有权限节点
     */
    function expandAllPermissionNode(){
        $("#permissionList").treegrid("expandAll");
    }

    /**
     * 折叠所有权限节点
     */
    function collapseAllPermissionNode(){
        $("#permissionList").treegrid("collapseAll");
    }

    /**
     * 新增角色弹出框
     */
    function addClientView() {
        var $editDialog = $('#roleEditDialog');
        $editDialog.iDialog({
            title: '新增角色',
            width: 880,
            height: 400,
            closed: false,
            cache: false,
            method: "get",
            href: contextPath + 'role/view/add',
            modal: true,
            buttons: [{
                text: '保存',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    $('#roleEditDialog').iForm('submit', {
                        url: contextPath + "role/2", //这里的 -2 只是一个占位符，无业务意义
                        success: function (data) {
                            var data = eval('(' + data + ')');
                            if (data.code == 200) {
                                $('#roleList').iDatagrid('reload');
                                $.iMessager.alert('提示', '新增成功', 'messager-success');
                                $editDialog.iDialog('close');
                            } else {
                                $.iMessager.alert('提示', data.msg, 'messager-error');
                                $('#roleList').iDatagrid('reload');
                                $editDialog.iDialog('close');
                            }
                            $("body").append("<form method=\"post\" id=\"roleEditDialog\"></form>");
                        }
                    });
                }
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $editDialog.iDialog('close');
                    $("body").append("<form method=\"post\" id=\"roleEditDialog\"></form>");
                }
            }]
        });
    }

    /**
     * 编辑角色
     */
    function roleEdit() {
        var roleCheckboxSelect = $("#roleList").treegrid("getChecked");
        if (roleCheckboxSelect == undefined || roleCheckboxSelect.length <= 0) {
            $.messager.alert("提示", "请选择一个角色", "messager-warning");
            return;
        }
        if (roleCheckboxSelect.length > 1) {
            $.messager.alert("提示", "只能选择一个角色", "messager-warning");
            return;
        }
        openEditDiag(roleCheckboxSelect[0].id);
    }

    /**
     * 操作一列的内容格式化
     */
    function operateFormatter(value, row, index) {
        var htmlstr = '<button class="layui-btn layui-btn-xs" onclick="openEditDiag(\'' + row.id + '\')">编辑</button>';
        htmlstr += '<button class="layui-btn layui-btn-xs layui-btn-danger" onclick="deleteClient(\'' + row.id + '\')">删除</button>';
        //htmlstr += '<button class="layui-btn layui-btn-xs" style="background-color:#2F4056" onclick="openRoleAuthorizeClientDiag(\'' + row.id + '\')">应用授权</button>';
        return htmlstr;
    }

    /**
     * 编辑角色
     */
    function openEditDiag(id) {
        var $editDialog = $('#roleEditDialog');
        $editDialog.iDialog({
            title: '角色编辑',
            width: 880,
            height: 400,
            closed: false,
            cache: false,
            method: "put",
            href: contextPath + 'role/' + id,
            modal: true,
            buttons: [{
                text: '保存',
                iconCls: 'fa fa-save',
                btnCls: 'topjui-btn-blue',
                handler: function () {
                    $('#roleEditDialog').iForm('submit', {
                        url: contextPath + "role/1",
                        success: function (data) {
                            var data = eval('(' + data + ')');
                            if (data.code == 200) {
                                $.iMessager.alert('提示', '操作成功', 'messager-success');
                                $('#roleList').iDatagrid('reload');
                                //tabMenuOprate(null,6);
                                $editDialog.iDialog('close');
                            } else {
                                $.iMessager.alert('提示', '系统错误，请稍后重试', 'messager-error');
                                $('#roleList').iDatagrid('reload');
                                $editDialog.iDialog('close');
                            }
                            $("body").append("<form method=\"post\" id=\"roleEditDialog\"></form>");
                        }
                    });
                }
            }, {
                text: '关闭',
                iconCls: 'fa fa-close',
                btnCls: 'topjui-btn-red',
                handler: function () {
                    $editDialog.iDialog('close');
                    $("body").append("<form method=\"post\" id=\"roleEditDialog\"></form>");
                }
            }]
        });
    }

    /**
     * 批量删除
     */
    function batchDeleteClient() {
        var roleCheckboxSelect = $("#roleList").treegrid("getChecked");
        if (roleCheckboxSelect == undefined || roleCheckboxSelect.length <= 0) {
            $.messager.alert("提示", "请选择角色", "messager-warning");
            return;
        }
        var roleIdArr = [];
        for (var i = 0; i < roleCheckboxSelect.length; i++) {
            roleIdArr.push(roleCheckboxSelect[i].id);
        }
        deleteClient(roleIdArr.join(","));
    }

    /**
     * 删除角色
     */
    function deleteClient(id) {
        $.iMessager.confirm('提示', '确定要删除吗?<p style="color: red;margin-top: 8px;">请慎重操作，删除后可能会影响相关系统的正常运行！如若没有特殊需求，请勿轻易删除！</p>', function (r) {
            if (r) {
                $.ajax({
                    url: contextPath + "role/batch", //路径
                    type: "post",
                    data: {
                        "roleId": id
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 200) {
                            $.iMessager.alert('提示', '删除成功', 'messager-success');
                            $('#roleList').iDatagrid('reload');
                        } else {
                            $.iMessager.alert('提示', '系统错误，请稍后重试', 'messager-error');
                        }
                    }
                });
            }
        });
    }

    //存储某角色所授权的应用client_id的集合
    var selectRoleClientAuthorize = [];
    /**
     * 为角色授权应用
     */
    function roleClientAuthorize(){
        if($("#selectRoleName").html() == "(暂未选择角色)"){
            $.messager.alert("提示", "请在上方角色列表中单击一条角色数据", "messager-warning");
            return;
        }
        var roleSelect = $("#roleList").datagrid("getSelections");
        //选中角色的ID
        var roleId = roleSelect[0].id;
        var clientIds = selectRoleClientAuthorize.join(",");
        $.iMessager.confirm('提示', '确定要为此角色赋予应用的访问权限吗?', function (r) {
            if (r) {
                $.ajax({
                    url: contextPath + "role/batch/client/authorize",
                    type: "post",
                    data: {
                        "clientId": clientIds,
                        "roleId": roleId
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 200) {
                            $.iMessager.alert('提示', '操作成功', 'messager-success');
                            $('#roleClientAuthorizeGird').treegrid('reload');
                            $('#clientList').treegrid('reload');
                            selectRoleClientAuthorize.length = 0;
                        } else {
                            $.iMessager.alert('提示',data.msg, 'messager-error');
                        }
                    }
                });
            }
        });
    }

    /**
     * 为角色授予应用的访问权限
     */
    function settingRoleClientPermission(){
        //获取选中的应用
        var selectRole =  $('#roleList').datagrid('getSelected');
        if(selectRole == null){
            $.messager.alert("提示", "请选择角色", "messager-warning");
            return;
        }
        //获取选中的应用
        var selectClient =  $('#clientList').treegrid('getSelected');
        if(selectClient == null){
            $.messager.alert("提示", "请选择应用", "messager-warning");
            return;
        }
        //判断权限数据是否为空
        var permissionData = $('#permissionList').treegrid("getData");
        if(permissionData == null || permissionData.length <= 0){
            $.messager.alert("提示", "暂无权限数据", "messager-warning");
            return;
        }
        //获取所有checkbox被选中的权限节点
        var checkedRoleClientPermissionList = $('#permissionList').treegrid('getCheckedNodes');
        var permissionIdArr = [];
        for(var i=0; i<checkedRoleClientPermissionList.length; i++){
            permissionIdArr.push(checkedRoleClientPermissionList[i].id);
        }
        //赋予权限请求操作
        $.iMessager.confirm('提示', '确定要设置操作权限吗?', function (r) {
            if (r) {
                $.ajax({
                    url: contextPath + "role/batch/client/permission",
                    type: "post",
                    data: {
                        "clientId": selectClient.id,
                        "roleId": selectRole.id,
                        "permissionId" : permissionIdArr.join(",")
                    },
                    dataType: 'json',
                    success: function (data) {
                        if (data.code == 200) {
                            $.iMessager.alert('提示', '操作成功', 'messager-success');
                            //$('#permissionList').treegrid('reload');
                        } else {
                            $.iMessager.alert('提示',data.msg, 'messager-error');
                        }
                    }
                });
            }
        });
    }
    /**
     * 为角色授权应用
     */
    /*function authorizeClient(){
        var roleCheckboxSelect = $("#roleList").treegrid("getChecked");
        if (roleCheckboxSelect == undefined || roleCheckboxSelect.length <= 0) {
            $.messager.alert("提示", "请选择一个角色", "messager-warning");
            return;
        }
        if (roleCheckboxSelect.length > 1) {
            $.messager.alert("提示", "只能选择一个角色", "messager-warning");
            return;
        }
        $("#roleOtherDetailTab ul li:eq(0)").click();
        //openRoleAuthorizeClientDiag(roleCheckboxSelect[0].id);
    }*/
    /**
     * 角色授权应用弹框
     */
    //function openRoleAuthorizeClientDiag(id){}
</script>
</body>
</html>